package com.mallcai.bigdata.ladon.service.export.impl.handler;

import com.cake.bigdata.starter.exception.category.BusinessException;
import com.mallcai.bigdata.ladon.service.export.impl.ExportContext;
import com.mallcai.bigdata.ladon.tools.FileUtil;
import com.mallcai.bigdata.ladon.utils.CompressZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * described : 将生成的文件进行压缩。并删除原来的文件
 *
 * @author CaKeDou
 * @date 2019-09-26 21:52
 * Modify:
 */
@Slf4j
@Component
@Order(900)
public class CompressHandler extends AbstractExportPostHandler {
    @Override
    public void postInternal(ExportContext context) {
        if (!context.getExportStrategy().isCompress()) {
            return;
        }
        try {
            String sourceFilePath = context.getFilePath();
            String zipFilePath = StringUtils.substringBefore(sourceFilePath, ".") + ".zip";
            CompressZipUtils.compressFile(sourceFilePath, zipFilePath);
            FileUtil.deleteFile(sourceFilePath);
            //设置新的文件名,文件路径会随之变化。
            context.setFileName(StringUtils.substringBefore(context.getFileName(), ".") + ".zip");
        } catch (Exception e) {
            log.error("压缩文件时出错", e);
            throw new BusinessException("压缩文件时出错");
        }
    }
}
